package com.banfeiguanli.springboot.mapper;

import com.banfeiguanli.springboot.entity.ExpenseApply;
import com.banfeiguanli.springboot.entity.dto.ExpenseApplyDTO;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ExpenseApplyMapper {
    //查询用户所在班级的申请记录
    @Select("select expApplyID, userInfo.UserName as applyUserName, ApplyAmount, ApplyReason, status, " +
            "ApplyTime, bjgly.UserName as auditUserName , AuditTime " +
            "from expenseapply, userinfo, bjgly " +
            "where EA_ClassAdminID in (select ClassAdminID from classadmin " +
            "where CA_ClassID = (select UI_ClassID from userinfo where UserID = #{userID})) " +
            "and EA_UserID = userInfo.UserID " +
            "and EA_ClassAdminID = ClassAdminID " +
            "and userInfo.UserName like concat('%',#{searchUser},'%') " +
            "and ApplyReason like concat('%',#{searchReason},'%') " +
            "order by ApplyTime desc " +
            "limit #{pageNumber}, #{pageSize}")
    List<ExpenseApply> getApplyRecord(@Param("userID") Integer userID,
                                      @Param("pageNumber") Integer pageNumber,
                                      @Param("pageSize") Integer pageSize,
                                      @Param("searchUser") String searchUser,
                                      @Param("searchReason") String searchReason);

    ////统计总数用于分页
    @Select("select count(*) " +
            "from expenseapply, userinfo " +
            "where EA_ClassAdminID in (select ClassAdminID from classadmin, userinfo " +
            "where CA_ClassID = (select UI_ClassID from userinfo where UserID = #{userID})) " +
            "and EA_UserID = UserID " +
            "and UserName like concat('%',#{searchUser},'%') " +
            "and ApplyReason like concat('%',#{searchReason},'%') ")
    Integer countClassApplyRecordTotal(@Param("userID") Integer userID,
                                       @Param("searchUser") String searchUser,
                                       @Param("searchReason") String searchReason);

    //申请班费
    @Insert("insert into expenseapply(ApplyAmount, ApplyTime, ApplyReason, status, EA_UserID, EA_ClassAdminID) " +
            "values (#{applyAmount},current_timestamp,#{applyReason}, '审核中', #{userID}, ( " +
            "select ClassAdminID " +
            "from ( " +
            "select * " +
            "from classadmin " +
            "where CA_ClassID = ( " +
            "select UI_ClassID " +
            "from userinfo " +
            "where UserID = #{userID}) " +
            "order by StartTime desc " +
            "limit 0, 1) ca)) ")
    Integer applyClassExpense(ExpenseApplyDTO expenseApplyDTO);

    //撤销班费申请
    @Update("update expenseapply set status = '撤销', AuditTime = current_timestamp " +
            "where ExpApplyID = #{expApplyID} and status = '审核中'")
    Integer cancelApply(Integer expApplyID);
}
